package com.wqy.netty.server;

import org.jboss.netty.channel.*;
import org.jboss.netty.handler.timeout.IdleState;
import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;
import org.jboss.netty.handler.timeout.IdleStateEvent;

import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * @Auther: WangQingyang
 * @Date: 2020/3/30 11:42
 * @Description:
 */
//public class HelloHandler extends IdleStateAwareChannelHandler implements ChannelHandler {
//    /**
//     * 会话状态事件
//     * @param ctx
//     * @param e
//     * @throws Exception
//     */
//    @Override
//    public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {
//        SimpleDateFormat dateFormat = new SimpleDateFormat("ss");
//        System.out.println(e.getState() + dateFormat.format(new Date()));
//        super.channelIdle(ctx, e);
//    }
//}

public class HelloHandler extends SimpleChannelHandler {
    /**
     * 这个和上面继承 IdleStateAwareChannelHandler 重写 channelIdle 方法一样
     * @param ctx
     * @param e
     * @throws Exception
     */
    @Override
    public void handleUpstream(final ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
        if (e instanceof IdleStateEvent){

            IdleStateEvent idleStateEvent = (IdleStateEvent)e;
            if(idleStateEvent.getState() == IdleState.ALL_IDLE){
                ChannelFuture write = ctx.getChannel().write("time out! you will close");
                write.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        ctx.getChannel().close();
                        System.out.println("替玩家下线");
                    }
                });


            }
            SimpleDateFormat dateFormat = new SimpleDateFormat("ss");
            System.out.println(idleStateEvent.getState() + dateFormat.format(new Date()));
        }else {
            super.handleUpstream(ctx, e);
        }
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        System.out.println(e.getMessage());
        super.messageReceived(ctx, e);
    }
}
